package com.recipedb.sprint.service.impl;

import com.recipedb.sprint.entity.PointRecords;
import com.recipedb.sprint.repository.PointRecordsRepository;
import com.recipedb.sprint.service.PointRecordsService;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PointRecordsServiceImpl implements PointRecordsService {

    private final PointRecordsRepository pointRecordsRepository;

    public PointRecordsServiceImpl(PointRecordsRepository pointRecordsRepository) {
        this.pointRecordsRepository = pointRecordsRepository;
    }

    /**
     * 获取用户所有积分及兑换记录列表
     */
    @Override
    public List<Map<String, Object>> getPointRecords(Long userid) {
        List<PointRecords> records = pointRecordsRepository.findByUseridOrderByCreatedAtDesc(userid);
        return records.stream().map(record -> {
            Map<String, Object> map = new HashMap<>();
            map.put("recordId", record.getRecordId());
            map.put("pointsChange", record.getPointsChange());
            map.put("sourceType", record.getSourceType());
            map.put("description", record.getDescription());
            map.put("relatedId", record.getRelatedId());
            map.put("quantity", record.getQuantity());
            map.put("createdAt", record.getCreatedAt());
            return map;
        }).collect(Collectors.toList());
    }

    /**
     * 查询单条积分或兑换记录详情
     */
    @Override
    public Map<String, Object> getRecordDetail(Long recordId) {
        PointRecords record = pointRecordsRepository.findById(recordId)
                .orElseThrow(() -> new RuntimeException("记录不存在"));

        Map<String, Object> map = new HashMap<>();
        map.put("recordId", record.getRecordId());
        map.put("userid", record.getUserid());
        map.put("pointsChange", record.getPointsChange());
        map.put("sourceType", record.getSourceType());
        map.put("description", record.getDescription());
        map.put("relatedId", record.getRelatedId());
        map.put("quantity", record.getQuantity());
        map.put("createdAt", record.getCreatedAt());
        return map;
    }

    /**
     * 保存积分或兑换记录
     */
    @Override
    public PointRecords saveRecord(PointRecords record) {
        record.setCreatedAt(LocalDateTime.now());
        return pointRecordsRepository.save(record);
    }

    /**
     * 按类型统计用户今日记录数量（用于限制每日奖励次数）
     */
    @Override
    public Long countTodayRecordsByType(Long userid, String sourceType) {
        LocalDate today = LocalDate.now();
        LocalDateTime startOfDay = today.atStartOfDay();
        LocalDateTime endOfDay = today.atTime(LocalTime.MAX);

        return pointRecordsRepository.countByUseridAndSourceTypeAndCreatedAtBetween(
                userid, sourceType, startOfDay, endOfDay);
    }

    /**
     * 获取单条记录实体
     */
    @Override
    public Optional<PointRecords> getRecordById(Long recordId) {
        return pointRecordsRepository.findById(recordId);
    }

    /**
     * 生成其他积分变动记录
     */
    @Override
    public void recordPoints(Long userid, Integer pointsChange, String sourceType, Long relatedId, Integer quantity, String description) {
        PointRecords record = new PointRecords(
                userid,
                pointsChange,
                sourceType,
                relatedId,
                quantity,
                description
        );
        record.setCreatedAt(LocalDateTime.now());
        pointRecordsRepository.save(record);
    }

    // 移除这个方法，因为现在由存储过程处理
    // @Override
    // public void recordRedemption(Long userid, Long relatedId, Integer pointsChange, String description, Integer quantity) {
    //     // 存储过程会自动插入兑换记录
    // }
}